package testingtool.multithread;

public class NotifyAndWait
{

    static Integer x = 1;

    public static void main( String[] args )
    {

        new Thread1( new NotifyAndWait() ).start();
        new Thread2( new NotifyAndWait() ).start();

    }

    public static Integer getX()
    {
        return NotifyAndWait.x;
    }

    public static void setX( Integer x )
    {
        NotifyAndWait.x = x;
    }
}

class Thread1 extends Thread
{
    NotifyAndWait value;

    public Thread1( NotifyAndWait aValue )
    {
        value = aValue;
    }

    @Override
    public void run()
    {
        while( true )
        {
            synchronized( NotifyAndWait.class )
            {
                if( String.valueOf( NotifyAndWait.getX() ).endsWith( "0" ) )
                {
                    System.out.println( "@" + NotifyAndWait.getX() );

                    NotifyAndWait.class.notify();
                    try
                    {
                        NotifyAndWait.class.wait();
                    }
                    catch( InterruptedException e )
                    {
                        e.printStackTrace();
                    }
                }
                else
                {
                    try
                    {
                        NotifyAndWait.class.wait();
                    }
                    catch( InterruptedException e )
                    {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}

class Thread2 extends Thread
{
    NotifyAndWait value;

    public Thread2( NotifyAndWait aValue )
    {
        value = aValue;
    }

    @Override
    public void run()
    {
        while( true )
        {
            synchronized( NotifyAndWait.class )
            {
                try
                {
                    sleep( 1000 );
                    NotifyAndWait.setX( NotifyAndWait.getX() + 1 );
                }
                catch( InterruptedException e )
                {
                    e.printStackTrace();
                }

                if( String.valueOf( NotifyAndWait.getX() ).endsWith( "0" ) )
                {
                    NotifyAndWait.class.notify();
                    try
                    {
                        NotifyAndWait.class.wait();
                    }
                    catch( InterruptedException e )
                    {
                        e.printStackTrace();
                    }

                }
                else
                {
                    System.out.println( "+" + NotifyAndWait.getX() );
                }

            }
        }
    }

}
